﻿using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
using GalaSoft.MvvmLight.Command;
using Looptribe.Moodlin8.Model;

namespace Looptribe.Moodlin8.ViewModel
{
    public class UserMessagesViewModel : LoadingViewModel
    {
        private User _user;
        public User User
        {
            set { Set(() => User, ref _user, value); }
            get { return _user; }
        }

        private readonly ObservableCollection<UserMessageWrapper> _messages = new ObservableCollection<UserMessageWrapper>();
        public ObservableCollection<UserMessageWrapper> Messages
        {
            get { return _messages; }
        }

        public ICommand SendCommand { get; private set; }

        public UserMessagesViewModel()
        {
            SendCommand = new RelayCommand<string>(ExecuteSend, a => !String.IsNullOrWhiteSpace(a));
        }

        public async void LoadContent(User user)
        {
            User = user;
            await Refresh();
        }

        public async override Task Refresh()
        {
            Messages.Clear();
            IsLoading = true;
            var messages = (await Api.GetMessagesAsync(User.Id)).Data;
            IsLoading = false;

            if (messages != null)
            {
                var filtered = messages
                    .OrderBy(a => a.TimeCreated);
                foreach (var wrappedObject in filtered.Select(a => new UserMessageWrapper(a,
                    a.UserIdFrom == CurrentUser.Id ? CurrentUser : User, a.UserIdFrom == CurrentUser.Id)))
                    Messages.Add(wrappedObject);
            }
        }

        private async void ExecuteSend(string message)
        {
            await Api.SendMessageAsync(User.Id, message);
            await Refresh();
        }
    }
}
